import {Component, ComponentFactoryResolver, ComponentRef, Input, OnDestroy, ViewContainerRef} from '@angular/core';

@Component({
  selector: 'app-container',
  template: ``
})
export class ContainerComponent implements OnDestroy {
  private currentComponent: ComponentRef<any>;
  constructor(
    private vcr: ViewContainerRef,
    private cfr: ComponentFactoryResolver
  ) {}
  @Input()
  set comp(data: { component: any, service?: any, inputs?: { [ key: string ]: any}, outputs?: { [ key: string ]: any}}){
    if (data && data.component) {
      const compFactory = this.cfr.resolveComponentFactory(data.component);
      const component = this.vcr.createComponent(compFactory);
      if (data.service) {
        component.instance['service'] = data.service;
      }
      if (data.inputs) {
        Object.keys(data.inputs).forEach(key => {
          component.instance[key] = data.inputs[key];
        });
      }
      if (data.outputs) {
        Object.keys(data.outputs).forEach(key => {
          component.instance[key] = data.outputs[key];
        });
      }
      this.destroy();
      this.currentComponent = component;
    }
  }
  destroy() {
    if (this.currentComponent) {
      this.currentComponent.destroy();
      this.currentComponent = null;
    }
  }
  ngOnDestroy() {
    this.destroy();
  }
}
